class TrainController < ApplicationController
  before_filter :sys_before_log

  #获取所有列车的信息，在读取列车列表的时候，不传递所有的交路信息，只把当前应该的交路信息发送到前端
  def getTrains
    total = Train.count
    nowDate = Time.now.to_date                                                  #得到当前日期
    trains = Train.findPage params[:start].to_i,params[:limit].to_i
    for train in trains                                                         #得到当前列车所跑的交路
      if(train.router_date)                                                     #如果有交路设置日期，就说明其交路已经设置
        sequence = ((nowDate - train.router_date) % train.router_number).to_i   #当前时间 - 交路设置时间的结果，和交路数取余，即可得到交路编号
        router = TrainRouter.findByTrainIdAndSequence(train.id,sequence).router #通过列车id和队列得到交路对象
        train.train_number = router.train_number                                #赋值给列车
        train.line = router.line                                                #赋值给列车
        train.length = router.length                                            #赋值给列车
      else                                                                      #如果没有设置交路日期，就说明没有设置交路，直接设置为未设置
        train.train_number = '未设置'                                            #赋值给列车
        train.line = '未设置'                                                    #赋值给列车
        train.length = 0                                                        #赋值给列车
      end
    end
    jsonStr="{train:"+trains.to_json()+",total:"+total.to_s+"}"
    render :text => jsonStr,:layout => false
  end

  def getTrainsForCombo
    forCBB = params[:for_cbb]
    
    sn = params[:query] || ''
    if forCBB.nil?
      trains = Train.where('sn like ?','%'+sn+'%')
      total = trains.length
    else
      trains = Train.where('is_locked = 0')
      total = Train.count
    end

    
    jsonStr="{train:"+trains.to_json(:only => [:id,:sn])+",total:"+total.to_s+"}"
    render :text => jsonStr,:layout => false
  end

  #创建列车
  def create
    begin
      train = Train.find_by_sn params[:sn]
      if train != nil
        info = '列车已存在，请更换！'
      else
        train = Train.new
        train.sn = params[:sn]
        train.train_type = params[:trainType]
        train.all_length = params[:all_length]
        train.last_length = params[:last_length]
        train.now_length = params[:now_length]
        train.xx_length = params[:xx_length]
        train.ts_length = params[:ts_length]
        train.two_level_fix_length = params[:two_level_fix_length]
        train.threex_length = params[:threex_length]
        train.fourx_length = params[:fourx_length]
        train.date = params[:date]
        train.save!
        info = 'success'
      end
    rescue Exception => e
      logger.info e
      info = '创建异常'
    end
    result = "{success:true,info:\"#{info}\"}"
    render :text => result,:layout => false
  end

  #删除列车信息
  def delete
    begin
      ids= params[:id][1..params[:id].length-2].split(',')
      Train.destroy(ids)
      info = 'success'
    rescue Exception=>e
      logger.info e
      info = '删除异常'
    end
    result = "{success:true,info:\"#{info}\"}"
    render :text=>result, :layout => false
  end

  #编辑列车信息
  def edit
    train = Train.find(params[:id])
    jsonStr = train.to_json()
    render :text=>jsonStr, :layout => false
  end

  #得到列车的交路信息
  def editTrainRouterData
    train = Train.find(params[:trainId])                                        #得到列车对象
    if TrainRouter.findByTrainIdAndSequence(params[:trainId], 0)                #如果存在排序为一的交路
      train.firstRouterId =
        TrainRouter.findByTrainIdAndSequence(params[:trainId],0).router_id      #将交路id进行保存
    end
    if TrainRouter.findByTrainIdAndSequence(params[:trainId], 1)                #如果存在排序为二的交路
      train.secondRouterId =
        TrainRouter.findByTrainIdAndSequence(params[:trainId],1).router_id      #将交路id进行保存
    end
    if TrainRouter.findByTrainIdAndSequence(params[:trainId], 2)                #如果存在排序为三的交路
      train.thirdRouterId =
        TrainRouter.findByTrainIdAndSequence(params[:trainId],2).router_id      #将交路id进行保存
    end
    jsonStr = train.to_json()
    render :text=>jsonStr, :layout => false
  end

  def update
    begin
      train = Train.find(params[:id])
      if train.sn == params[:sn].to_s                                           #如果编号已经没有改动
        train.train_type = params[:trainType]
        train.all_length = params[:all_length]
        train.last_length = params[:last_length]
        train.now_length = params[:now_length]
        train.xx_length = params[:xx_length]
        train.ts_length = params[:ts_length]
        train.two_level_fix_length = params[:two_level_fix_length]
        train.threex_length = params[:threex_length]
        train.fourx_length = params[:fourx_length]
        train.date = params[:date]
        train.save!
        info = 'success'
      else                                                                      #如果编号改动了
        trainSN = Train.find_by_sn params[:sn]                                  #以新编号为基准查找对象
        if trainSN == nil                                                       #如果对象为空，则可以更改
          train.sn = params[:sn]
          train.train_type = params[:trainType]
          train.all_length = params[:all_length]
          train.last_length = params[:last_length]
          train.now_length = params[:now_length]
          train.xx_length = params[:xx_length]
          train.ts_length = params[:ts_length]
          train.two_level_fix_length = params[:two_level_fix_length]
          train.threex_length = params[:threex_length]
          train.fourx_length = params[:fourx_length]
          train.date = params[:date]
          train.save!
          info = 'success'
        else
          info = '该列车编号已存在，请更换！'
        end
      end
    rescue Exception=>e
      logger.info e
      info = '更新异常'
    end
    result = "{success:true,info:\"#{info}\"}"
    render :text=>result, :layout=>false
  end

  #将列车设为停留，一旦设为停留，则列车之前所有的交路组合被清空
  def setStay
    begin
      train = Train.find(params[:trainId])
      train.router_date = Time.now.to_date                                      #得到当前日期
      train.router_number = 1
      train.save!
      trainRouters = TrainRouter.find_all_by_train_id(params[:trainId])         #根据id找到对象
      for trainRouter in trainRouters                                           #删除掉所有关于此列车的router
        trainRouter.destroy
      end
      trainRouter = TrainRouter.new
      trainRouter.router_id = 1
      trainRouter.train_id = params[:trainId]
      trainRouter.sequence = 0
      trainRouter.save!
      info = 'success'
    rescue Exception=>e
      logger.info e
      info = '操作异常'
    end
    result = "{success:true,info:\"#{info}\"}"
    render :text=>result, :layout=>false
  end

  def xx                                                                        #镟修功能，将镟修长度设为0
    train = Train.find(params[:trainId])
    train.xx_length = 0                                                         #将列车上的镟修后长度设为0
    train.save!
    result = "{success:true,info:\"success\"}"
    render :text=>result, :layout=>false
  end

  def ts                                                                        #探伤功能，将探伤长度设为0
    train = Train.find(params[:trainId])
    train.ts_length = 0                                                         #将列车上的镟修后长度设为0
    train.save!
    result = "{success:true,info:\"success\"}"
    render :text=>result, :layout=>false
  end

  def threex                                                                    #三级修功能，将三级修长度设为0
    train = Train.find(params[:trainId])
    train.threex_length = 0                                                     #将列车上的镟修后长度设为0
    train.save!
    result = "{success:true,info:\"success\"}"
    render :text=>result, :layout=>false
  end

  def fourx                                                                     #四级修功能，将四级修长度设为0
    train = Train.find(params[:trainId])
    train.fourx_length = 0                                                      #将列车上的镟修后长度设为0
    train.save!
    result = "{success:true,info:\"success\"}"
    render :text=>result, :layout=>false
  end

  #锁定或解锁列车，列车不允许删除，只允许锁定。
  def doLock
    ids= params[:id][1..params[:id].length-2].split(',')
    for id in ids
      train = Train.find(id)
      if train.is_locked == 1
        train.is_locked = 0
      else
        train.is_locked = 1
      end
      train.save!
    end
    info = "success"
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

end